<?php

$inc_core = realpath(dirname(__FILE__) . '/../inc/inc_core.inc');
require_once $inc_core;
use teia\webdev\php\core as teia;

$result = teia\SessionWrapper::start();

if (!$result) {
	echo "Session Error: Failed to start session\n";
}
// Force https access
if (FORCE_HTTPS) teia\FunctionPool::force_https_access();

// error texts
global $login_auth_err_txt;
global $login_form_err_txt;
global $signup_regist_err_txt;
global $signup_form_err_txt;
global $on_signup_url;
global $on_login_url;

if (!isset($login_auth_err_txt)) $login_auth_err_txt = 'Log-in failed: Invalid email/password conbination!';
if (!isset($login_form_err_txt)) $login_form_err_txt = 'Log-in failed: You must fill out all fields!';
if (!isset($signup_regist_err_txt)) $signup_regist_err_txt = 'Sign-up failed: Unable to commit registration data!';
if (!isset($signup_form_err_txt)) $signup_form_err_txt = 'Sign-up failed: You must fill out all fields correctly!';

$err_msg = isset($_REQUEST['err_msg']) ? $_REQUEST['err_msg'] : '';

// url to follow after sucessful log-in or sign-up
if (isset($_REQUEST['redirect_url'])) {
	$on_signup_url = $_REQUEST['redirect_url'];
	$on_login_url = $_REQUEST['redirect_url'];
} else {
	if (!isset($on_signup_url))
		$on_signup_url = isset($_REQUEST['on_signup_url']) ? $_REQUEST['on_signup_url'] : ON_SIGNUP_URL;
	if (!isset($on_login_url))
		$on_login_url = isset($_REQUEST['on_login_url']) ? $_REQUEST['on_login_url'] : ON_LOGIN_URL;
}

function display_forms($signup_txt_array=NULL, $login_txt_array=NULL, $err_msg='') {
	echo "\n<div class=\"login_signup_form\">\n";
	// display error message, if any
	if (!empty($err_msg)) {
		echo "<p id='err_msg'>$err_msg</p>\n";
	}
	// call sign-up form
	teia\FunctionPool::display_signup_form($signup_txt_array);
	// call log-in form
	teia\FunctionPool::display_login_form($login_txt_array);
	// end forms
	echo "</div>\n";
}

function handle_login_form() {
	// use globally defined vars
	$on_login_url = $GLOBALS['on_login_url'];
	$login_auth_err_txt = $GLOBALS['login_auth_err_txt'];
	$login_form_err_txt = $GLOBALS['login_form_err_txt'];

	// isset($_REQUEST['email']) && isset($_REQUEST['password']) && !empty($_REQUEST['email']) && !empty($_REQUEST['password'])
	if (teia\FunctionPool::validate_request_vars(array('email', 'password'))) {
		$usr_id = $_REQUEST['email'];
		$usr_pwd = $_REQUEST['password'];
		try {
			$user = teia\SessionWrapper::get_user();
			$pass = $user->login($usr_id, $usr_pwd);
			if ($pass) {
				// log-in successful, go to redirect url
				header("Location: $on_login_url");
			} else {
				display_forms(null,null,$login_auth_err_txt);
			}
		} catch (Exception $e) {
			display_forms(null,null, $e->getMessage() . ' [' . $e->getCode() . ']');
		}
	} else {
		display_forms(null, null, $login_form_err_txt);
	}
}

function handle_signup_form() {
	// use globally defined vars
	$on_signup_url = $GLOBALS['on_signup_url'];
	$signup_regist_err_txt = $GLOBALS['signup_regist_err_txt'];
	$signup_form_err_txt = $GLOBALS['signup_form_err_txt'];

	if (!teia\FunctionPool::array_empty_value($_REQUEST) && isset($_REQUEST['gender'])) {
		// create short name for form variables
		$disp_name = $_REQUEST['display_name'];
		$usr_id = $_REQUEST['email'];
		$usr_pwd = $_REQUEST['password_1'];
		$rep_pwd = $_REQUEST['password_2'];
		$bday = $_REQUEST['birthday'];
		$gender = $_REQUEST['gender'];

		if (!teia\FunctionPool::validate_email($usr_id)) {
			display_forms(null,null,$signup_regist_err_txt . " [E-mail]");
			return;
		}

		if (!parse_password($usr_pwd, $rep_pwd)) {
			return;
		}

		$date_time = parse_birthday($bday);
		if (!$date_time) {
			return;
		}
		if ($gender != 'M' && $gender != 'F') {
			display_forms(null, null, null); // ignore unknown gender
			return;
		}
		try {
			$birthday = parse_birthday($bday);
			if (!$birthday) {
				return;
			}

			$user = teia\FunctionPool::get_session_user();
			$pass = $user->signup($usr_id, 'Default', $usr_pwd, $disp_name, $usr_id, 'Registered');
			if ($pass) {
				$pass = teia\UserProfile::create_basic_profile($usr_id, 'Default', $birthday, $gender);
				if (!$pass) {
					echo
				"<p>
				The sign-up was successful, but a slight problem occurred during the creation of the user profile.
											Please update your profile later.
									</p>\n";
					// sign-up event
					return;
				}
				// sign-up successful, go to redirect url
				header("Location: $on_signup_url");
			} elseif (mysql_errno() == 1062){
				display_forms(null, null, $signup_form_err_txt . 'E-mail already used!');
			} else {
				display_forms(null, null, $signup_form_err_txt);
			}
		} catch (Exception $e) {
			if ($e->getCode() == 1062) {
				display_forms(null, null, $signup_form_err_txt . 'E-mail already used!');
			} else {
				display_forms(null, null, $signup_form_err_txt);
			}
		}
	} else {
		display_forms(null, null, $signup_form_err_txt);
	}
}

function parse_password($password_1, $password_2) {
	$pasword_check = teia\FunctionPool::password_check($password_1, $password_2);

	switch ($pasword_check) {
		case teia\PasswordCheck::PASS:
			return true;
		case teia\PasswordCheck::TOO_SHORT:
			display_forms(null,null, PWD_TOO_SHORT_ERR_TXT);
			return false;
		case teia\PasswordCheck::TOO_LONG:
			display_forms(null,null, PWD_TOO_LONG_ERR_TXT);
			return false;
		case teia\PasswordCheck::PATTERN_MISMATCH:
			display_forms(null,null, PWD_PAT_MISMATCH_ERR_TXT);
			return false;
		case teia\PasswordCheck::REPETITION_MISMATCH:
			display_forms(null,null, PWD_REP_MISMATCH_ERR_TXT);
			return false;
		default:
			display_forms(null,null,$signup_form_err_txt . " [Password]");
		return false;
	}
}

function parse_birthday($bday) {
	try {
		$date = teia\FunctionPool::validate_date_str($bday);
		return $date;
	} catch (Exception $e) {
		echo INVALID_DATETIME_ERR_TXT . " [" . $e->getMessage(). "]";
		return true;
	}
}

?>

<!-- Internal style -->
<style type="text/css">
<!--

#err_msg {
	text-align: center;
	border-style: solid;
	border-width: medium;
	border-color: red;
	display: block;
}

.login_signup_form {
	margin-left: 100px;
	margin-right: 100px;
}

#usr_login_form {
	float: right;
	width: 50%;
}

#usr_signup_form {
	float: left;
	width: 50%;
}

fieldset.form_fieldset {
	
}

label.input_label {
	width: 10em;
	float: left;
	text-align: right;
	margin-right: 0.5em;
	display: block;
}

.input_field {
	width: 15em;
	text-align: left;
	margin-left: 0.5em;
}

.date_field {
	text-align: left;
	margin-left: 0.5em;
}

span.input_field {
	margin-left: 0.5em;
}

.terms_privacy {
	text-align: center;
}
 
.login_help {
	margin-left: 5.5em;
}

.signup_submit, .login_submit {
	margin-left: 11em;
	margin-top: 0.5em;
}

-->
</style>

<?php

// decide what and how to display
if (isset($_REQUEST['form_name'])) {
	$form_name = $_REQUEST['form_name'];
	
	if ($form_name == 'login_form') {
		// process log-in form
		handle_login_form();
	} elseif ($form_name == 'signup_form') {
		// process sign-up form
		handle_signup_form();
	} else {
		// unexpected form, ignore it and display forms
		display_forms(null, null, $err_msg);
	}
} else {
	// first pass, no form submitted
	display_forms(null, null, $err_msg);
}
?>
